package com.yuqiangz.sync;

/**
 * @author 赵雨强
 * @create 2021/7/10 9:51
 *
 * 核心逻辑是线程操作资源类，对资源类进行加锁
 */


public class SaleTicket {
    public static void main(String[] args) {
        //创建Ticket对象
        Ticket ticket = new Ticket();
        //创建三个线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                //调用卖票方法
                for (int i = 0; i < 40; i++) {
                    ticket.sale();
                }
            }
        },"AA").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                //调用卖票方法
                for (int i = 0; i < 40; i++) {
                    ticket.sale();
                }
            }
        },"BB").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                //调用卖票方法
                for (int i = 0; i < 40; i++) {
                    ticket.sale();
                }
            }
        },"CC").start();
    }
}


class Ticket{
    private int number = 30;

    public synchronized void sale(){
        if (number > 0){
            System.out.println(Thread.currentThread().getName()+" : 卖出第："+(number--)+
                    " 剩下："+number);
        }
    }
}